/**
 * React的双向绑定
 */

import React from "react";

class App extends React.PureComponent {
  state = {
    inputValue: "",
    checkedArr: [],
  };

  changeInputValue = () => {
    this.setState({
      inputValue: "hello",
    });
  };

  handleCheck = (e) => {
    console.log(e);
    console.log(e.target.value);
    const _newArr = [...this.state.checkedArr];
    if (e.target.checked) {
      _newArr.push(e.target.value);
    } else {
      _newArr.splice(_newArr.indexOf(e.target.value), 1);
    }
    this.setState(
      {
        checkedArr: _newArr,
      },
      () => {
        console.log(this.state.checkedArr);
      }
    );
  };

  handleCheckbox = () => {
    this.setState({
      checkedArr: ["选项二"],
    });
  };

  render() {
    return (
      <div className="App">
        <div>输入的值:{this.state.inputValue}</div>
        <button onClick={this.changeInputValue}>改变值，手动值</button>
        <input
          value={this.state.inputValue}
          onInput={(e) => {
            console.log(e.target.value);
            this.setState({
              inputValue: e.target.value,
            });
          }}
        ></input>
        <input
          checked={this.state.checkedArr.includes("选项一")}
          value="选项一"
          onChange={this.handleCheck}
          type="checkbox"
          name="choose"
        ></input>
        选项一
        <input
          checked={this.state.checkedArr.includes("选项二")}
          onChange={this.handleCheck}
          type="checkbox"
          name="choose"
          value="选项二"
        ></input>
        选项2
        <input
          checked={this.state.checkedArr.includes("选项三")}
          onChange={this.handleCheck}
          type="checkbox"
          name="choose"
          value="选项三"
        ></input>
        选项3
        <input
          checked={this.state.checkedArr.includes("选项四")}
          onChange={this.handleCheck}
          type="checkbox"
          name="choose"
          value="选项四"
        ></input>
        选项四
        <div></div>
        <button onClick={this.handleCheckbox}>双向绑定checkbox</button>
      </div>
    );
  }
}

export default App;
